'use strict'

const dbUtil = require('../util/dbUtil');
const mysqlUtil = require('../util/mysqlUtil');
const Q = require('q');

/**
 * 查询
 */
let query = (req, res) => {
    let sql = "select sp.*, p.id as project_id, p.code as project_code, p.name as project_name, pp.deploy_userid, pp.deploy_username, pp.is_finish_deploy, ";
    sql += "date_format(sp.create_time,'%Y-%m-%d %T') as create_time_display, date_format(sp.publish_time,'%Y-%m-%d %T') as publish_time_display, ";
    sql += "date_format(pp.deploy_time,'%Y-%m-%d %T') as deploy_time_display, pp.id as package_project_id, pp.is_verification ";
    sql += "from t_ug_simple_package sp ";
    sql += "left join t_ug_package_project pp on pp.package_id = sp.id ";
    sql += "left join t_ug_project p on p.id = pp.project_id ";
    sql += "where is_publish=1 ";

    let searchVal = mysqlUtil.paramFilter(req.body.searchVal);

    if (req.body.packageProjectId != null && req.body.packageProjectId != '') {
        sql += " and p.id=" + mysqlUtil.escape(req.body.packageProjectId);
    }
    if (searchVal != null && searchVal != '') {
        sql += " and (sp.name like '%" + searchVal + "%' or sp.module like '%" + searchVal + "%' or sp.description like '%" + searchVal + "%')";
    }

    if (req.body.is_finish_deploy != null && req.body.is_finish_deploy != '') {
        if (req.body.is_finish_deploy == 1) {
            sql += " and pp.is_finish_deploy=1";
        } else if (req.body.is_finish_deploy == 0) {
            sql += " and (pp.is_finish_deploy=0 or pp.is_finish_deploy is null)";
        }
    }
    if (req.body.is_verification != null && req.body.is_verification != '') {
        if (req.body.is_verification == 1) {
            sql += " and pp.is_verification=1";
        } else if (req.body.is_finish_deploy == 0) {
            sql += " and (pp.is_verification=0 or pp.is_verification is null)";
        }
    }

    sql += " order by sp.create_time desc, p.code asc";

    dbUtil.partitionQuery(sql, req, res);
};

/**
 * 查看升级包
 */
let info = (req, res) => {
    var id = req.query.id;
    var packageProjectId = req.query.packageProjectId;

    var _getInfo = () => {
        let deferred = Q.defer();
        mysqlUtil.exec("select sp.*, date_format(sp.create_time,'%Y-%m-%d %T') as create_time_display, date_format(sp.publish_time,'%Y-%m-%d %T') as publish_time_display from t_ug_simple_package sp where id =?", [id], (err, result) => {
            deferred.resolve(result[0]);
        });
        return deferred.promise;
    };

    _getInfo().done(function(data) {
        data.packageProjectId = packageProjectId;
        res.render('simpleDownUpgradePackage/info', { package: data });
    });
};


/**
 * 下载上传的压缩包
 */
let downloadZipFile = (req, res) => {
    let id = req.query.id;

    let _getFilePath = () => {
        let deferred = Q.defer();
        mysqlUtil.exec("select * from t_ug_simple_package where id=?", [id], (err, result) => {
            if (err || result.length == 0) {
                res.render('404', { errMsg: 'Can\'t find the file.' });
                return;
            }
            deferred.resolve({ filePath: result[0].file_path, fileName: result[0].name });
        });
        return deferred.promise;
    };
    _getFilePath().done(d => {
        res.download(d.filePath, d.fileName);
    });
};

/**
 * 确认完成部署
 */
let doFinishDeploy = (req, res) => {
    let id = req.body.id; // packageProjectId

    // 更新完成部署状态
    let _update = () => {
        let deferred = Q.defer();
        mysqlUtil.exec("update t_ug_package_project set is_finish_deploy=1, deploy_userid=?, deploy_username=?, deploy_time=now() where id=?", [req.session.user.id, req.session.user.name, id], (err, result) => {
            deferred.resolve();
        });
        return deferred.promise;
    };


    // 开始处理
    _update().done(data => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: true }));
    }, (data) => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false }));
    });
};

/**
 * 确认完成验证
 */
let doFinishValidate = (req, res) => {
    let id = req.body.id; // packageProjectId

    // 更新完成部署状态
    let _update = () => {
        let deferred = Q.defer();
        mysqlUtil.exec("update t_ug_package_project set is_verification=1 where id=?", [id], (err, result) => {
            deferred.resolve();
        });
        return deferred.promise;
    };


    // 开始处理
    _update().done(data => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: true }));
    }, (data) => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false }));
    });
};


exports.query = query;
exports.info = info;
exports.downloadZipFile = downloadZipFile;
exports.doFinishDeploy = doFinishDeploy;
exports.doFinishValidate = doFinishValidate;